(function (window, $, undefined) {
  'use strict';

  var roleData = {};

  var $tableRole = $('#table-role');

  var menuData = [];

  main(function () {

    util.jqGrid($tableRole, {
      url: ajaxURL.SYSTEM + '/sys/v1/role/getList',
      // datatype: 'json',
      autowidth: true,
      height: $(window).height() - 280,
      multiselect: true,
      multiboxonly: true,
      // shrinkToFit: false,
      colModel: [
        { label: '编号', name: 'kid', key: true, width: 50, hidden: true },
        { label: '角色名称', name: 'name', width: 100 },
        { label: '角色描述', name: 'description', width: 400, formatter: function (v, o, r) {
          return '<span>' + util.safeHTML(v) + '</span>';
        } },
        { label: '添加时间', name: 'createTime', width: 100, formatter: function (v, o, r) {
          return util.dateFormat(v);
        } }
      ],
      // pager: '#pager-role',
      loadComplete: function (res) {
        roleData = {};
        if (res && res.data) {
          $.each(res.data, function (_, item) {
            roleData[item.kid] = item;
          });
        }
      }
    });

    function searchTable() {
      var name = $('#search-name').val();
      util.searchGrid($tableRole, {
        name: name
      });
    }

    $('#btn-search').click(searchTable);
    util.onEnter('#search-name', searchTable);

    // 菜单树结构
    util.get(ajaxURL.SYSTEM + '/sys/v1/menu/queryAll', function (res) {
      // 菜单数据转换
      menuData.length = 0;
      $.each(res.data, function (_, item) {
        menuData.push({
          kid: item.kid,
          pid: item.pid,
          name: item.name,
          levels: item.levels,
          _url: item.url
        });
      });

      searchTable();
    });

    // 初始化树结构
    function initMenuTree(data) {
      var settings = {
        data: {
          simpleData: {
            enable: true,
            idKey: 'kid',
            pIdKey: 'pid',
            rootPId: null
          }
        },
        check: {
          enable: true
        },
        view: {
          showLine: true,
          showIcon: true,
          dblClickExpand: true,
          selectedMulti: false
        }
      }
      $.fn.zTree.init($('#menu-tree'), settings, data);
    }

    var $layerRole = $('#layer-role');
    var $formRole = $('#form-role');
    var $validateRole = $formRole.validate({
      rules: {
        name: { required: true, maxlength: 20 },
        description: { maxlength: 80 }
      },
      messages: {
        name: { required: '请输入角色名称', maxlength: '角色名称长度限制 20' },
        description: { maxlength: '描述字数限制为 80' }
      }
    });

    $('#btn-add').click(function () {
      util.resetForm($formRole);
      util.layerOpen2({
        title: '添加角色',
        content: $layerRole,
        area: ['600px', ''],
        btn: ['添加', '取消'],
        yes: function (index) {
          var data = util.formData($formRole);
          if ($validateRole.form() && isCheckName(data.name)) {

            util.post(ajaxURL.SYSTEM + '/sys/v1/role/save', {
              createId: oUser.userId,
              name: data.name,
              description: data.description
            }, function (res) {
              util.tip.success('添加成功');
              layer.close(index);
              $('#search-name').val('');
              searchTable();
            });
          }
        }
      });
    });

    // 重名校验
    function isCheckName(name, id) {
      var ret = true;
      $.each(roleData, function (_, role) {
        if (role.name === name && id !== role.kid) {
          ret = false;
          util.tip.warn('名称存在冲突，请重新填写');
          return false;
        }
      });
      return ret;
    }

    // 修改角色
    $('#btn-edit').click(util.oneCheck($tableRole, function (id, data) {

      var curData = roleData[id];

      util.resetForm($formRole);
      util.fillForm($formRole, curData);
      util.layerOpen2({
        title: '修改角色',
        content: $layerRole,
        area: ['600px', ''],
        btn: ['修改', '取消'],
        yes: function (index) {
          var data = util.formData($formRole);
          if ($validateRole.form() && isCheckName(data.name, +id)) {
            util.post(ajaxURL.SYSTEM + '/sys/v1/role/update', {
              createId: oUser.userId,
              kid: id,
              name: data.name,
              description: data.description
            }, function (res) {
              util.tip.success('修改成功');
              layer.close(index);
              $tableRole.trigger('reloadGrid');
            });
          }
        }
      });
    }));

    // 删除角色
    $('#btn-del').click(util.oneCheck($tableRole, function (id, data) {
      layer.confirm('确认删除该角色，删除后其关联的设置将全部失效，请谨慎操作。', function () {
        util.ajax(ajaxURL.SYSTEM + '/sys/v1/role/delete?roleId=' + id, '', 'DELETE', util.resCallback(function (res) {
          util.tip.success('删除成功');
          $tableRole.trigger('reloadGrid');
        }));
      });
    }));

    var $layerPermission = $('#layer-permission');

    // 权限分配操作
    $('#btn-permission').click(util.oneCheck($tableRole, function (id, data) {
      $.fn.zTree.destroy('menu-tree');
      getCurMenuList(id);

      util.layerOpen2({
        title: '权限分配操作，当前选择角色：' + data.name,
        content: $layerPermission,
        area: ['600px', '400px'],
        btn: ['确认分配', '取消'],
        yes: function (index) {
          var treeObj = $.fn.zTree.getZTreeObj('menu-tree');
          var nodes = treeObj.getCheckedNodes(true);
          var menuList = [];
          $.each(nodes, function (_, item) {
            menuList.push({
              createId: oUser.userId,
              roleId: id,
              menuId: item.kid
            });
          });
          layer.confirm('确定设置角色：【' + data.name + '】的权限配置信息？', function () {
            util.post(ajaxURL.SYSTEM + '/sys/v1/roleMenu/update', menuList, function (res) {
              layer.close(index);
              util.tip.success('设置成功');
            });
          });
        }
      });
    }));

    // 获取当前选择的角色的菜单列表
    function getCurMenuList(id) {
      util.get(ajaxURL.SYSTEM + '/sys/v1/role/get', {
        roleId: id
      }, function (res) {
        var curMenuData = [];
        var menuList = [];
        if (res.data && res.data.menuList) {
          $.each(res.data.menuList, function (_, item) {
            menuList.push(item.menuId);
          });
        }
        $.each(menuData, function (_, item) {
          curMenuData.push($.extend(true, item, {
            checked: menuList.indexOf(item.kid) !== -1
          }));
        });

        initMenuTree(curMenuData);
      });
    }

  });

})(window, jQuery);
